/*
 * é Copyright 2011 Romain Marteau, Matthieu Totet
 * 
 *    This file is part of VineaToum.
 *
 *    VineaToum is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    VineaToum is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with VineaToum.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.vineatoum.view.stateView;

import java.awt.GridBagLayout;
import javax.swing.JLabel;

import org.vineatoum.business.Parcelle;
import org.vineatoum.business.Plantation;
import org.vineatoum.business.action.ActionDescriptor;
import org.vineatoum.business.action.abstraction.Analyse;
import org.vineatoum.business.action.analyse.Prelevement;
import org.vineatoum.business.configuration.LieuDit;
import org.vineatoum.business.configuration.MaturityMeasureType;
import org.vineatoum.controller.ActionController;
import org.vineatoum.controller.IActionController;
import org.vineatoum.model.abstraction.IVineaToumModel;
import org.vineatoum.observer.IObserverAction;
import org.vineatoum.view.action.RecolteActionPanel;
import org.vineatoum.view.action.PrelevementPanel;
import org.vineatoum.view.component.JAccordion;
import org.vineatoum.view.component.TrackingPanel;
import org.vineatoum.view.utils.JPanelWrapped;
import org.vineatoum.view.utils.jtablecustom.JTableCustom;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Label;

import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PlantationActionPanel extends JPanelWrapped implements IObserverAction {
	private static final long serialVersionUID = -5445564122111066285L;

	protected JLabel lblTitle;
	protected JLabel lblName;
	protected JLabel lblCepage;
	protected JLabel lblLieuDit;
	protected JLabel lblAppellation;
	protected JLabel lblSurface;
	protected JAccordion accordion;
	
	protected JPanel dataPanel;
	protected JPanel actionPanel;
	protected JTabbedPane tabPanel;
	protected TrackingPanel trackingPanel;
	
	protected IVineaToumModel model;
	protected IActionController controller;
	protected LieuDit lieuDit;

	protected JLabel lblDensitCepDensity;
	protected JLabel lblCepGap;
	protected JLabel lblRowGap;
	protected JTableCustom<Prelevement> tablePrelevements;
	protected JTable tableRecoltes;
	protected JButton btnFaireUnPrlvement;
	protected JButton btnFaireUneRcolte;
	protected JLabel lblParcelles;
	
	protected JToolBar toolBarActions;

	/**
	 * Create the panel.
	 */
	public PlantationActionPanel(final IVineaToumModel model, final Plantation plantation) {
		DecimalFormat df = new DecimalFormat("########.##");

		this.model = model;
		this.model.addObserver(this);

		this.controller = new ActionController(model);
		
		//BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
		//SpringLayout layout = new SpringLayout();
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		
		

		dataPanel = new JPanel();
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
		gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
		gridBagLayout.columnWeights = new double[] { 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0,
				1.0, Double.MIN_VALUE };
		gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
		dataPanel.setLayout(gridBagLayout);
		{
			lblTitle = new JLabel("Vue Plantation");
			GridBagConstraints gbc_lblVuePlantation = new GridBagConstraints();
			gbc_lblVuePlantation.insets = new Insets(0, 0, 5, 5);
			gbc_lblVuePlantation.gridx = 2;
			gbc_lblVuePlantation.gridy = 0;
			dataPanel.add(lblTitle, gbc_lblVuePlantation);
		}
		{
			lblName = new JLabel("Nom : " + plantation.getName());
			GridBagConstraints gbc_lblVuePlantation = new GridBagConstraints();
			gbc_lblVuePlantation.insets = new Insets(0, 0, 5, 5);
			gbc_lblVuePlantation.gridx = 2;
			gbc_lblVuePlantation.gridy = 1;
			dataPanel.add(lblName, gbc_lblVuePlantation);
		}
		{
			lblSurface = new JLabel(df.format(plantation.getSurfaceArea()) + " hectares");
			GridBagConstraints gbc_lblVuePlantation = new GridBagConstraints();
			gbc_lblVuePlantation.insets = new Insets(0, 0, 5, 5);
			gbc_lblVuePlantation.gridx = 6;
			gbc_lblVuePlantation.gridy = 1;
			dataPanel.add(lblSurface, gbc_lblVuePlantation);
		}
		{
			lblDensitCepDensity = new JLabel(plantation.getCepDensity() + " ceps/hectare");
			GridBagConstraints gbc_lblDensitDeCep = new GridBagConstraints();
			gbc_lblDensitDeCep.insets = new Insets(0, 0, 5, 5);
			gbc_lblDensitDeCep.gridx = 7;
			gbc_lblDensitDeCep.gridy = 1;
			dataPanel.add(lblDensitCepDensity, gbc_lblDensitDeCep);
		}
		{
			lblRowGap = new JLabel("Ecartement des rangs : " + df.format(plantation.getRowGap())
					+ " m");
			GridBagConstraints gbc_lblRowgap = new GridBagConstraints();
			gbc_lblRowgap.insets = new Insets(0, 0, 5, 5);
			gbc_lblRowgap.gridx = 7;
			gbc_lblRowgap.gridy = 2;
			dataPanel.add(lblRowGap, gbc_lblRowgap);
		}
		{
			lblCepage = new JLabel("Cépage : " + plantation.getCepage());
			GridBagConstraints gbc_lblVuePlantation = new GridBagConstraints();
			gbc_lblVuePlantation.insets = new Insets(0, 0, 5, 5);
			gbc_lblVuePlantation.gridx = 2;
			gbc_lblVuePlantation.gridy = 3;
			dataPanel.add(lblCepage, gbc_lblVuePlantation);
		}
		{
			lblAppellation = new JLabel("Appellation : " + plantation.getAppellation());
			GridBagConstraints gbc_lblVuePlantation = new GridBagConstraints();
			gbc_lblVuePlantation.insets = new Insets(0, 0, 5, 5);
			gbc_lblVuePlantation.gridx = 4;
			gbc_lblVuePlantation.gridy = 3;
			dataPanel.add(lblAppellation, gbc_lblVuePlantation);
		}
		{
			lblCepGap = new JLabel("Ecartement des ceps : " + df.format(plantation.getCepGap())
					+ " m");
			GridBagConstraints gbc_lblCepggap = new GridBagConstraints();
			gbc_lblCepggap.insets = new Insets(0, 0, 5, 5);
			gbc_lblCepggap.gridx = 6;
			gbc_lblCepggap.gridy = 2;
			dataPanel.add(lblCepGap, gbc_lblCepggap);
		}
		{
			lblParcelles = new JLabel("Parcelles :");
			GridBagConstraints gbc_lblParcelles = new GridBagConstraints();
			gbc_lblParcelles.insets = new Insets(0, 0, 5, 5);
			gbc_lblParcelles.gridx = 4;
			gbc_lblParcelles.gridy = 4;
			dataPanel.add(lblParcelles, gbc_lblParcelles);
		}
		{
			JPanel panelParcelles = new JPanel();
			//FIXME Apply a layout manager to have the parcelles in a column. Don't know why the boxLayout doesn't work
			for (Iterator<Parcelle> iterator = plantation.getParcelles().iterator(); iterator.hasNext();) {
				Parcelle parcelle = (Parcelle) iterator.next();
				JLabel lblParcelleTmp = new JLabel(parcelle.getName() + " - " + parcelle.getCadastralNumber());
				panelParcelles.add(lblParcelleTmp);
				lieuDit = parcelle.getPlaceName();
			}

			GridBagConstraints gbc_txtAreaParcelles = new GridBagConstraints();
			gbc_txtAreaParcelles.fill = GridBagConstraints.HORIZONTAL;
			gbc_txtAreaParcelles.gridwidth = 4;
			gbc_txtAreaParcelles.insets = new Insets(0, 0, 5, 5);
			gbc_txtAreaParcelles.gridx = 5;
			gbc_txtAreaParcelles.gridy = 4;
			dataPanel.add(panelParcelles, gbc_txtAreaParcelles);
		}
		{
			if (lieuDit != null) {
				JLabel lblLieuDit = new JLabel("Lieu dit : " + lieuDit.getName());
				GridBagConstraints gbc_lblParcelles = new GridBagConstraints();
				gbc_lblParcelles.insets = new Insets(0, 0, 5, 5);
				gbc_lblParcelles.gridx = 2;
				gbc_lblParcelles.gridy = 4;
				dataPanel.add(lblLieuDit, gbc_lblParcelles);
			}
		}		
		{
			tabPanel = new JTabbedPane();
			
			tablePrelevements = new JTableCustom<Prelevement>(new Prelevement()) {
				private static final long serialVersionUID = 1L;

				protected boolean fireEditingStarted(final JTableCustom<Prelevement> table,
						final int row, int column) {
					table.getCellEditor().stopCellEditing();
					final PrelevementPanel prelevementPanel = new PrelevementPanel(model,
							(Prelevement) table.getValueAt(row));
					Object[] options = { "OK", "Annuler" };
					int n = JOptionPane.showOptionDialog(getRootPane(), prelevementPanel,
							"Ajouter", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
							null, options, options[0]);
					if (n == JOptionPane.OK_OPTION) {
						table.setValueAt(prelevementPanel.getDate(), row, 0);
						table.setValueAt(prelevementPanel.getMaturity(), row, 1);
						table.setValueAt(
								prelevementPanel.getMeasurementType(), row, 2);
						table.setValueAt(prelevementPanel.getAcidity(), row, 3);
						table.setValueAt(prelevementPanel.getEstimatedDate(), row,
								4);
						table.setValueAt(prelevementPanel.getEstimatedYield(), row, 5);
						table.setValueAt(prelevementPanel.getComment(), row, 6);
					}

					return false;
				}
			};

			// FIXME
			List<Prelevement> prelevements = new ArrayList<Prelevement>();
			for (Iterator<Analyse> iterator = plantation.getAnalyses().iterator(); iterator.hasNext();) {
				Analyse analyse = (Analyse) iterator.next();
				prelevements.add((Prelevement) analyse);

			}
			tablePrelevements.setData(prelevements);
			
			JPanel panel = new JPanel(new BorderLayout());
			panel.add(tablePrelevements, BorderLayout.CENTER);
			panel.add(tablePrelevements.getTableHeader(), BorderLayout.NORTH);
			
			tabPanel.addTab("Prélévement", panel);
			

			tableRecoltes = new JTable();
			JPanel panelRecoltes = new JPanel(new BorderLayout());
			panelRecoltes.add(tableRecoltes, BorderLayout.CENTER);
			panelRecoltes.add(tableRecoltes.getTableHeader(), BorderLayout.NORTH);

			tabPanel.addTab("Récoltes", panelRecoltes);
			
			JPanel pan = new JPanel(new BorderLayout());
			pan.add(new Label("Graphes é venir"));
			tabPanel.addTab("Graphes", pan);
		}
		{
			btnFaireUnPrlvement = new JButton("Faire un pr\u00E9l\u00E8vement");
			btnFaireUnPrlvement.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					final PrelevementPanel prelevementPanel = new PrelevementPanel(model,
							new Prelevement());
					Object[] options = { "OK", "Annuler" };
					int n = JOptionPane.showOptionDialog(getRootPane(), prelevementPanel,
							"Ajouter", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
							null, options, options[0]);
					if (n == JOptionPane.OK_OPTION) {
						Prelevement prelevement = new Prelevement();
						try {
							prelevement.setDate(prelevementPanel.getDate());
							prelevement.setMaturity((Float) prelevementPanel.getMaturity());
							prelevement.setMeasureType((MaturityMeasureType) prelevementPanel.getMeasurementType());
							prelevement.setAcidity((Float) prelevementPanel.getAcidity());
							prelevement.setEstimatedHarvestDate(prelevementPanel.getEstimatedDate());
							prelevement.setEstimatedYield((Float) prelevementPanel.getEstimatedYield());
							prelevement.setComment(prelevementPanel.getComment());
						} catch (ClassCastException e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						tablePrelevements.addRow(prelevement);
						ActionDescriptor action = new ActionDescriptor(prelevement);
						action.addVinInput(plantation, 100);

						controller.addAction(action);
					}

				}
			});
		}
		{
			//TODO
			btnFaireUneRcolte = new JButton("Faire une r\u00E9colte");
			btnFaireUneRcolte.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					final RecolteActionPanel recolteActionPanel = new RecolteActionPanel();
					Object[] options = { "OK", "Annuler" };
					int n = JOptionPane.showOptionDialog(getRootPane(), recolteActionPanel,
							"R\u00E9colte", JOptionPane.OK_CANCEL_OPTION,
							JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
					if (n == JOptionPane.OK_OPTION) {
						Prelevement prelevement = new Prelevement();
						try {

						} catch (ClassCastException e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						tablePrelevements.addRow(prelevement);
					}

				}
			});			
		}
		{
			toolBarActions = new JToolBar();
			toolBarActions.setOrientation(SwingConstants.VERTICAL);
			
			toolBarActions.add(btnFaireUnPrlvement);
			toolBarActions.add(btnFaireUneRcolte);
		}
		{
			actionPanel = new JPanel(new BorderLayout());
			
			actionPanel.add(tabPanel, BorderLayout.CENTER);
			actionPanel.add(toolBarActions, BorderLayout.WEST);
		}
		{
			trackingPanel = new TrackingPanel(plantation);
			
			accordion = new JAccordion();
			accordion.addBar("Action", actionPanel);
			accordion.addBar("Historique", trackingPanel);
	
			add(dataPanel);
			add(accordion);
		}
	}

	@Override
	public void doWhenWrapperCancelClick() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doWhenWrapperOkClick() {
		// TODO Auto-generated method stub

	}
	
	

}
